package Writer

import (
	"fmt"
	"github.com/influxdata/influxdb/client/v2"
	"log"
	"log_process/system"
)

type InfluxDBWriter struct {
	Addr      string
	Username  string
	Password  string
	Database  string
	Precision string
}

func (writer *InfluxDBWriter) Write(writerChan chan *system.Message) {

	var (
		err    error
		c      client.Client
		bp     client.BatchPoints
		po     *client.Point
		data   *system.Message
		tags   map[string]string
		fields map[string]interface{}
	)

	if c, err = client.NewHTTPClient(client.HTTPConfig{
		Addr:     writer.Addr,
		Username: writer.Username,
		Password: writer.Password,
	}); err != nil {
		system.TypeMonitorChan <- system.TypeErrNum
		panic(fmt.Sprintf("NewHTTPClient error：%s", err.Error()))
	}

	defer c.Close()

	for data = range writerChan {

		if bp, err = client.NewBatchPoints(client.BatchPointsConfig{
			Precision: writer.Precision,
			Database:  writer.Database,
		}); err != nil {
			system.TypeMonitorChan <- system.TypeErrNum
			panic(fmt.Sprintf("NewBatchPoints error：%s", err.Error()))
		}

		tags = map[string]string{"Path": data.Path, "Method": data.Method, "Scheme": data.Scheme, "Status": data.Status}

		fields = map[string]interface{}{
			"UpstreamTime": data.UpstreamTime,
			"RequestTime":  data.RequestTime,
			"BytesSent":    data.BytesSent,
		}

		if po, err = client.NewPoint("nginx_log", tags, fields, data.TimeLocal); err != nil {
			log.Println(fmt.Sprintf("NewPoint error：%s", err.Error()))
			system.TypeMonitorChan <- system.TypeErrNum
			continue
		}

		bp.AddPoint(po)

		if err = c.Write(bp); err != nil {
			log.Println(fmt.Sprintf("Write error：%s", err.Error()))
			system.TypeMonitorChan <- system.TypeErrNum
			continue
		}

		log.Println("write success!")
	}
}
